package com.itbaizhan.shopping_message_service.service;

import co.elastic.clients.elasticsearch.xpack.usage.Base;
import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponseBody;
import com.itbaizhan.shopping_common.result.BaseResult;
import com.itbaizhan.shopping_common.service.MessageService;
import darabonba.core.client.ClientOverrideConfiguration;
import lombok.SneakyThrows;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;

/**
 * 短信验证码服务
 */
@DubboService
@Service
public class MessageServiceImpl implements MessageService {
	
	@Value("${message.accessKeyId}")
	private String accessKeyId;
	@Value("${message.accessKeySecret}")
	private String accessKeySecret;
	
	/**
	 * 发送短信验证码
	 * @param phoneNumber 手机号
	 * @param code 验证码
	 * @return
	 */
	@SneakyThrows
	public BaseResult sendMessage(String phoneNumber, String code) {
		
		// 配置凭证认证信息，包括ak, secret, token
		StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
				// 请确保环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID 和 ALIBABA_CLOUD_ACCESS_KEY_SECRET 已设置。
				.accessKeyId(accessKeyId)
				.accessKeySecret(accessKeySecret)
				//.securityToken(System.getenv("ALIBABA_CLOUD_SECURITY_TOKEN")) // 使用 STS token
				.build());
		// 配置客户端
		AsyncClient client = AsyncClient.builder()
				.region("cn-qingdao") // Region区域 ID
				//.httpClient(httpClient) // 使用配置的 HttpClient，否则使用默认的 HttpClient (Apache HttpClient)
				.credentialsProvider(provider)
				//.serviceConfiguration(Configuration.create()) // 服务级别的配置
				// 客户端级别的配置重写，可以设置 Endpoint, Http 请求参数等。
				.overrideConfiguration(
						ClientOverrideConfiguration.create()
								// Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
								.setEndpointOverride("dysmsapi.aliyuncs.com")
						//.setConnectTimeout(Duration.ofSeconds(30))
				)
				.build();
		// API 请求参数设置
		SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
				.signName("阿里云短信测试")
				.templateCode("SMS_154950909")//模板码
				.phoneNumbers(phoneNumber)
				.templateParam("{\"code\":\"" + code + "\"}")
				// 请求级别的配置重写，可以设置 Http 请求参数等。
				// .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
				.build();
		// 异步获取 API 请求的返回值
		CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
		// 同步获取 API 请求的返回值
		SendSmsResponse resp = response.get();
		System.out.println(new Gson().toJson(resp));
		
		
		// 最后，关闭客户端
		client.close();
		
		//对发送结果进行封装成BaseResult对象
		SendSmsResponseBody respBody = resp.getBody();
		
		if ("OK".equals(respBody.getCode())) {
			return new BaseResult(200, respBody.getCode(), respBody.getMessage());
		} else {
			return new BaseResult(500, respBody.getCode(), respBody.getMessage());
		}
		
	}
}
